<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>案例_地区查询</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css">
  <style>
    :root {
      font-size: 15px;
    }

    body {
      padding-top: 15px;
    }
  </style>
</head>

<body>
  <div class="container">
    <form id="editForm" class="row">
      <!-- 输入省份名字 -->
      <div class="mb-3 col">
        <label class="form-label">省份名字</label>
        <input type="text" value="北京" name="province" class="form-control province" placeholder="请输入省份名称" />
      </div>
      <!-- 输入城市名字 -->
      <div class="mb-3 col">
        <label class="form-label">城市名字</label>
        <input type="text" value="北京市" name="city" class="form-control city" placeholder="请输入城市名称" />
      </div>
    </form>
    <button type="button" class="btn btn-primary sel-btn">查询</button>
    <br><br>
    <p>地区列表: </p>
    <ul class="list-group">
      <!-- 示例地区 -->
      <li class="list-group-item">东城区</li>
    </ul>
  </div>
  <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
  <script>
    /**
     * 目标: 根据省份和城市名字, 查询对应的地区列表
    */
    const selBtn = document.querySelector('.sel-btn')
    selBtn.addEventListener('click', () => {
      const province = document.querySelector('.province').value
      const city = document.querySelector('.city').value
      const obj = {
        pname: province,
        cname: city
      }
      const paramsobj = new URLSearchParams(obj)
      const querystring = paramsobj.toString()
      console.log(querystring)
      const xhr = new XMLHttpRequest()
      xhr.open('get', `http://hmajax.itheima.net/api/area?${querystring}`, true)
      xhr.onreadystatechange = function () {
        if (xhr.readyState === 4 && xhr.status === 200) {
          const res = JSON.parse(xhr.response)// 对象
          console.log(res)// 对象
          const list = res.list// 数组
          console.log(list)// 数组
          const htmlstr = list.map(item => `<li class="list-group-item">${item}</li>`).join('')
          document.querySelector('.list-group').innerHTML = htmlstr
        }
      }
      xhr.send()
    })

  </script>
</body>

</html>